define(['ionic'], function () {
    angular.module('myApp', ['ionic'])
        .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
            $stateProvider
                .state('home', {
                    url: '/home/:id',
                    templateUrl: 'view/home.html',
                    controller: 'HomeCtrl'
                })
                .state('uncheckdetail', {
                    cache:false,
                    url: '/uncheckdetail',
                    templateUrl: 'view/uncheckdetail.html',
                    controller: 'DetailCtr'
                })
                .state('checkdetail', {
                    cache:false,
                    url: '/checkdetail',
                    templateUrl: 'view/checkdetail.html',
                    controller: 'DetailCtr'
                });
            $urlRouterProvider.otherwise('/home/');

            $ionicConfigProvider.platform.android.navBar.alignTitle('center');
            $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.android.navBar.transition('view');
            $ionicConfigProvider.platform.android.views.transition('ios');
            $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
            $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
            $ionicConfigProvider.platform.android.tabs.style('standard');
            $ionicConfigProvider.platform.android.tabs.position('bottom');
            $ionicConfigProvider.platform.android.form.toggle('large');
            $ionicConfigProvider.views.forwardCache(false);
            $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.default.backButton.text(false);
        })
        .run(function ($q) {
            localStorage.activebtn?"":localStorage.activebtn=false;
            try{
                u9.registerGetContactFn && u9.registerGetContactFn('Approval', getContact);

                function getContact() {
                    var defer = $q.defer();

                    var docId = JSON.parse(localStorage.getItem('theone')).entity_id;
                    if (!docId) {
                        defer.resolve([]);
                    } else {
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGRestMultiCallSV.MultiCall.IGetJoinUserInfo',
                            params: [docId, true],
                            onSuccess: function (data) {
                                var temp = [];
                                angular.forEach(data, function (chat) {
                                    if (chat.UserID > 1) {
                                        temp.push({
                                            name: chat.UserName,
                                            phone: chat.UserPhone
                                        });
                                    }
                                });
                                defer.resolve(temp);
                            },
                            onFailure: function (err) {
                                defer.reject(err);
                            }
                        });
                    }

                    return defer.promise;
                }
            }catch(err){
                console.log(err)
            }
        })
        .value('isLoading',true)
        .factory('getClientData', ['$ionicLoading', '$http', function ($ionicLoading, $http) {
            var Data = {
                displayNum: 8,
                token: u9.getLoginData().token,
                port: u9.getConnectSetting().port,
                adress: u9.getConnectSetting().address

            };
            var baseUrl="http://" + Data.adress + ":" + Data.port + "/workflow.aspx";
            Data.uncheckUrl =baseUrl+"?count=" + Data['displayNum'] + "&token=" + Data.token;
            Data.checkedUrl = baseUrl+ "/GetApprovedlist?count=" + Data['displayNum'] + "&token=" + Data.token;
            Data.checkedSearch=baseUrl + "/GetApprovedlist?is_approved=1start_time=1970-01-01&end_time=2100-09-04&count=" + Data['displayNum'] + "&token=" + Data.token;
            Data.uncheckSearch= baseUrl+ "?SearchFlowList?is_approved=0start_time=1970-01-01&end_time=2100-09-04&count=" + Data['displayNum'] + "&token=" + Data.token;
            Data.AttachFile=baseUrl + "/DownAttachmentFile?&token=" + Data.token;
            Data.doAgree=baseUrl+"/SubmitApprovalInfo?&token=" + Data.token;
            Data.doTransmit=baseUrl+"/SubmitApprovalInfo?&token=" + Data.token;
            Data.initData=baseUrl+"/SearchUserlist?&token=" + Data.token;
            function newGetData(page, type) {
                var random=Math.random();
                var url = Data[type + 'Url'];
                url += "&start=" + page+"&random="+random;
                return $http.get(url, {'timeout': 20000})
            }
            function getSearchData(page,value,type){
                var url = Data[type + 'Url'];
                url += "&start=" + page+'&search_info='+value;
                return $http.get(url,{'timeout': 20000})
            }
            function getAttachFile(id){
                var url = Data['AttachFile']+ "&FileID=" +id;
                return $http.get(url,{'timeout': 20000})
            }
            function doAgree(id,type,index,opinion){
                var url = Data['doAgree']+ "&entity_id=" +id+'&entity_type='+type+"&action="+index+"&opinion="+opinion;
                return $http.get(url,{'timeout': 20000})
            }
            function doTransmit(id,type,opinion,value){
                var url = Data['doTransmit']+ "&entity_id=" +id+'&entity_type='+type+"&action=8&opinion="+opinion+"&user_list=" +value;
                return $http.get(url,{'timeout': 20000})
            }
            function initData(searchText){
                var url = Data['initData']+ "&userInfo=" +searchText;
                return $http.get(url,{'timeout': 20000})
            }
            return {
                newGetData: newGetData,
                getSearchData: getSearchData,
                getAttachFile:getAttachFile,
                doAgree:doAgree,
                doTransmit:doTransmit,
                initData:initData,
                relateDate: {'_token': Data.token, 'address': Data.adress, 'port': Data.port},
            }


        }])
        .directive('handerBubble', function ($ionicScrollDelegate) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    $('#hander-nav').click(function () {
                        $ionicScrollDelegate.scrollBottom(true);
                        if ($('#hander-ul li:eq(0)').css('opacity') == 0) {
                            $('#hander-ul li:eq(0)').css({
                                'opacity': 1,
                                '-webkit-transform': 'translate(0px, -60px) rotate(720deg)',
                                '-webkit-transition': 'all 0.5s'
                            });
                            $('#hander-ul li:eq(1)').css({
                                'opacity': 1,
                                '-webkit-transform': 'translate(-55px, -25px) rotate(720deg)',
                                '-webkit-transition': 'all 0.5s'
                            });
                            $('#hander-ul li:eq(2)').css({
                                'opacity': 1,
                                '-webkit-transform': 'translate(-52px, 30px) rotate(720deg)',
                                '-webkit-transition': 'all 0.5s'
                            });
                            $('#hander-ul li:eq(3)').css({
                                'opacity': 1,
                                '-webkit-transform': 'translate(0px, 60px) rotate(720deg)',
                                '-webkit-transition': 'all 0.5s'
                            });
                        } else {
                            $('#hander-ul li:eq(0)').css({
                                'opacity': 0,
                                '-webkit-transform': 'translate(0px, 0px) rotate(-720deg)',
                                '-webkit-transition': 'all 0.4s'
                            });
                            $('#hander-ul li:eq(1)').css({
                                'opacity': 0,
                                '-webkit-transform': 'translate(0px, 0px) rotate(-720deg)',
                                '-webkit-transition': 'all 0.4s'
                            });
                            $('#hander-ul li:eq(2)').css({
                                'opacity': 0,
                                '-webkit-transform': 'translate(0px, 0px) rotate(-720deg)',
                                '-webkit-transition': 'all 0.4s'
                            });
                            $('#hander-ul li:eq(3)').css({
                                'opacity': 0,
                                '-webkit-transform': 'translate(0px, 0px) rotate(-720deg)',
                                '-webkit-transition': 'all 0.4s'
                            });
                        }
                    })
                }
            }
        })
        .controller('HomeCtrl',HomeCtrl )
        .controller('DetailCtr', DetailFactory);
    HomeCtrl.$inject=['$state', '$scope', 'getClientData','isLoading'];
    DetailFactory.$inject = ['$scope', 'getClientData', '$state', '$ionicModal','$ionicHistory'];
    function HomeCtrl($state, $scope, getClientData,isLoading) {
        var self=this;
        $scope.searchModel={
            uncheckinfo:"",
            checkedinfo:""
        }
        $scope.uncheckinfo = $scope.checkinfo = '';
        $scope.unchecklist = [];
        $scope.checkedlist = [];
        $scope.loadOver={
            uncheck: true,
            checked: true
        }
        $scope.record = {
            uncheck: 0,
            checked: 0
        }
        $scope.obj={
            Scrolled:true
        }
        self.enScroll = {
            uncheck: true,
            checked: true
        }
        function switchActive(type) {
            switch (type) {
                case true:
                    $scope.btn = {
                        checked: true,
                        defaultbtnleft: 'btn-left-active',
                        defaultbtnright: 'btn-right-default'
                    };
                    break;
                case false:
                    $scope.btn = {
                        checked: false,
                        defaultbtnleft: 'btn-left-default',
                        defaultbtnright: 'btn-right-active'
                    };
            }
            $scope.obj.Scrolled=true;
        }
        function remoteSuccessCallback(res,type,refresh){
                var data=res.data;
                u9.hideLoading();
                if (data.status_code == 401) {
                    u9.alert("状态过期了,请重新登陆系统");
                    self.enScroll[type] = false;
                    $scope.loadOver[type]=false;
                }
                if (!data.flow_instance_list) {
                    u9.alert("服务器出问题了");
                    self.enScroll[type] = false;
                    $scope.loadOver[type]=false;
                }
                if(data.flow_instance_list.length==0){
                    self.enScroll[type] = false;
                    $scope.loadOver[type]=false;
                }
                if (data.flow_instance_list && data.flow_instance_list.length && data.flow_instance_list.length > 0) {
                    if(refresh){
                        $scope[type + 'list'] = data.flow_instance_list;
                    }else{
                        $scope[type + 'list'] = $scope[type + 'list'].concat(data.flow_instance_list);
                    }
                    self.enScroll[type] = true;

                    $scope.record[type]++;

                }
                $scope.$broadcast(eventName);

        }
        function failureCallback(type){
            self.enScroll[type] = false;
            u9.hideLoading();
            u9.alert("请求失败了");
        }
        function getRemoteData(type,eventName,refresh){
            if(isLoading){
                isLoading=false;
            }else{
                u9.showLoading();
            }
            if(!self.enScroll[type]&&!refresh){
                $scope.obj.Scrolled=false;
                u9.hideLoading();
            }else{

                getClientData.newGetData($scope.record[type], type)
                    .then(function (res) {
                        var data=res.data;
                        u9.hideLoading();
                        if (data.status_code == 401) {
                            u9.alert("状态过期了,请重新登陆系统");
                            self.enScroll[type] = false;
                            $scope.loadOver[type]=false;
                            $scope.obj.Scrolled=false;
                        }
                        if (!data.flow_instance_list) {
                            u9.alert("服务器出问题了");
                            self.enScroll[type] = false;
                            $scope.loadOver[type]=false;
                            $scope.obj.Scrolled=false;
                        }
                        if(data.flow_instance_list.length==0){
                            self.enScroll[type] = false;
                            $scope.loadOver[type]=false;
                            $scope.obj.Scrolled=false;
                        }
                        if (data.flow_instance_list && data.flow_instance_list.length && data.flow_instance_list.length > 0) {
                            if(refresh){
                                $scope[type + 'list'] = data.flow_instance_list;
                            }else{
                                $scope[type + 'list'] = $scope[type + 'list'].concat(data.flow_instance_list);
                            }
                            self.enScroll[type] = true;

                            $scope.record[type]++;

                        }
                        /* $scope.$broadcast(eventName);*/
                    },function (res) {
                        // $scope.$broadcast(eventName);
                        self.enScroll[type] = false;
                        u9.hideLoading();
                        $scope.obj.Scrolled=false;
                        u9.alert("请求失败了");

                    })['finally'](function(){
                    $scope.$broadcast(eventName);

                })
            }


        }
        function getSearchData(type,eventName,refresh){
            u9.showLoading();
            getClientData.getSearchData($scope.record[type],$scope.searchModel[type+'info'],type).then(function(res){
                remoteSuccessCallback(res,type,refresh);
            },function(res){
                failureCallback(type);
            })['finally'](function(){
                if(eventName){
                    $scope.$broadcast(eventName);
                }
            })
        }
        $scope.saveOneInfo = function (x, state) {
            window.localStorage.theone = JSON.stringify(x);
            $state.go(state)
        };
        $scope.doRefresh = function () {
            var type = $scope.btn.checked ? "uncheck" : "checked";
            $scope.record[type]=0;
            self.enScroll[type]=true;
            getRemoteData(type,'scroll.refreshComplete',true);
            return;
            /*******华丽丽的分割线留备用的**********/
            if($scope.searchModel[type+'info']){
                getSearchData(type,'scroll.refreshComplete');
            }else{
                getRemoteData(type,'scroll.refreshComplete');
            }
        };
        $scope.changeActive = function (type) {
            switchActive(type);
            localStorage.activebtn = type;
        }
        switchActive(eval(localStorage.activebtn));
        $scope.loadMore = function () {
            var type = $scope.btn.checked ? "uncheck" : "checked";
            //if(!self.enScroll[type]) return;
            getRemoteData(type,'scroll.infiniteScrollComplete');
            //return
            /*******华丽丽的分割线留备用的**********/
           /* if($scope.searchModel[type+'info']){
                getSearchData(type,'scroll.infiniteScrollComplete');
            }else{
                getRemoteData(type,'scroll.infiniteScrollComplete');
            }*/


        };
        /********华丽丽的分割线下面的代码是用来查找后台的*********/
        $scope.getSearchData=function(){
            var type=$scope.btn.checked?"uncheck":"checked";
            $scope.record[type]=0;
            getSearchData(type,"",true);
        }

    }
    function DetailFactory($scope, getClientData, $state, $ionicModal,$ionicHistory) {
        $scope.user = {
            opinion: ''
        };
        $scope.IsBottom = false;
        $scope.info = {
            search: '',
            checkevalue: ''
        };
        $scope.searchresults = [];
        $scope.noresultflag = false;
        $scope.toggleGroup = function (group) {
            if ($scope.isGroupShown(group)) {
                $scope.shownGroup = null;
            } else {
                $scope.shownGroup = group;
            }
            $scope.IsBottom = false;
        };
        $scope.isGroupShown = function (group) {
            return $scope.shownGroup === group;
        };

        $scope.toggleGroup2 = function (group) {
            if ($scope.isGroupShown2(group)) {
                $scope.shownGroup2 = null;
            } else {
                $scope.shownGroup2 = group;
            }
            $scope.IsBottom = false;
        };
        $scope.isGroupShown2 = function (group) {
            return $scope.shownGroup2 === group;
        };

        $scope.toggleGroup3 = function (group) {
            if ($scope.isGroupShown3(group)) {
                $scope.shownGroup3 = null;
            } else {
                $scope.shownGroup3 = group;
            }
            $scope.IsBottom = false;
        };
        $scope.isGroupShown3 = function (group) {
            return $scope.shownGroup3 === group;
        };

        $scope.toggleGroup4 = function (group) {
            if ($scope.isGroupShown4(group)) {
                $scope.shownGroup4 = null;
            } else {
                $scope.shownGroup4 = group;
            }
            $scope.IsBottom = false;
        };
        $scope.isGroupShown4 = function (group) {
            return $scope.shownGroup4 === group;
        };

        $scope.datalist = JSON.parse(localStorage.getItem('theone'))
        $scope.loadMore = function () {
            $scope.IsBottom = true;
            $scope.$broadcast('scroll.infiniteScrollComplete');
        };
        $scope.listinit = function () {
            $scope.resultlist = [];
            $scope.resultlist2 = [];
            for (var prop in $scope.datalist.doc_data) {
                if (typeof($scope.datalist.doc_data[prop]) == 'object') {
                    $scope.resultlist = $scope.datalist.doc_data[prop];
                }
                else {
                    $scope.resultlist2.push({'title': prop, 'value': $scope.datalist.doc_data[prop]});
                }
            }
        };
        function openFile(path, filename) {
            if (!path) {
                u9.alert("文件地址不存在");
                return;
            }
            var fileUri = 'http://' + getClientData.relateDate.address + ':' + getClientData.relateDate.port + '/u9_gateway' + path;
            window.parent.open(fileUri, '_system');
            return;
            //备用方案
            //dispatchFile(fileUri);
            function iosOpen(fileUri) {
                if (parent.window.cordova.InAppBrowser) {
                    parent.window.cordova.InAppBrowser.open(fileUri, '_blank', 'location=no');
                } else {
                    window.parent.open(fileUri, '_system');
                }
            }

            function androidOpen(fileUri) {
                var filer = parent.window.FileTransfer ? new parent.window.FileTransfer() : '', path = parent.window.cordova.file.externalApplicationStorageDirectory + filename;
                if (!filer || !path) {
                    u9.alert('error');
                    return;
                }
                filer.download(encodeURI(fileUri), path, function (entry) {
                    parent.window.plugins.fileOpener.open(entry.toURL());
                }, function (error) {
                    u9.alert('下载文件出错了');
                })
            }

            function dispatchFile(fileUri) {
                if (parent.device.platform.toLowerCase() == "android") {
                    androidOpen(fileUri);
                } else {
                    iosOpen(fileUri);
                }

            }
        }

        $scope.getAttachFile = function (id, filename) {
            getClientData.getAttachFile(id)
                .success(function (data) {
                    if (data.status_code && data.status_code == '500') {
                        u9.alert("获取文件路径出错");
                        return;
                    }
                    openFile(data, filename);
                })
                .error(function (data) {
                    u9.alert(data);
                })
        };
        $scope.doAgree = function (index) {
            getClientData.doAgree($scope.datalist.entity_id,$scope.datalist.entity_type,index,$scope.user.opinion)
                .success(function (data) {
                    if (data.status_code == '200') {
                        $ionicHistory.nextViewOptions({
                            disableBack: true
                        })
                        $ionicHistory.clearHistory();
                        $ionicHistory.clearCache();
                        $state.go('home',{id:Math.random()},{reload:true});
                    } else {

                        u9.alert(data.status_message);
                    }
                })
                .error(function (data) {
                    u9.alert(data.status_message);
                });
        };
        //show modal
        $ionicModal.fromTemplateUrl('modal.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.modal = modal;
        });

        $scope.initData = function () {
            getClientData.initData($scope.info.search)
                .success(function (data) {
                    if (data.user_list.length == 1) {
                        $scope.noresultflag = true;
                    } else {
                        $scope.noresultflag = false;
                        $scope.searchresults = data.user_list;
                    }
                })
                .error(function (data) {
                    u9.alert(data.status_message);
                });
        };
        //transmit option
        $scope.doTransmit = function (u) {
            getClientData.doTransmit($scope.datalist.entity_id,$scope.datalist.entity_type,$scope.user.opinion,u.checkevalue)
                .success(function (data) {
                    if (data.status_code == '200') {
                        $ionicHistory.nextViewOptions({
                            disableBack: true
                        })
                        $ionicHistory.clearHistory();
                        $ionicHistory.clearCache();
                        $state.go('home',{id:Math.random()},{reload:true});
                    } else {
                        //alert('doTransmit success exception:'+data.status_message);
                        u9.alert(data.status_message);
                    }
                })
                .error(function (data) {
                    //alert('doTransmit error:'+data.status_message);
                    u9.alert(data.status_message);
                });
            $scope.modal.hide();
        };
        $scope.listinit();
    }
});
